package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.dao.CardInfoDao;
import com.sq.partner.manager.dao.FacadeAppFormDao;
import com.sq.partner.manager.dao.FacadeTempPolicyDao;
import com.sq.partner.manager.mybatis.model.ActirationCardActivated;
import com.sq.partner.manager.mybatis.model.ActirationCardBatchInsuredDto;
import com.sq.partner.manager.mybatis.model.ActirationCardDifinition;
import com.sq.partner.manager.mybatis.model.CardInfo;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.DictOccupDto;
import com.sq.partner.manager.mybatis.model.FacadeAppApplicant;
import com.sq.partner.manager.mybatis.model.FacadeAppForm;
import com.sq.partner.manager.mybatis.model.FacadeAppFormExtend;
import com.sq.partner.manager.mybatis.model.FacadeAppInsured;
import com.sq.partner.manager.mybatis.model.FacadeTempPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.ActirationCardActivatedService;
import com.sq.partner.manager.service.ActirationCardApplyService;
import com.sq.partner.manager.service.ActirationCardPreviewService;
import com.sq.partner.manager.service.FacadeTempPolicyService;
import com.sq.partner.manager.service.NlifeRiskService;
import com.sq.partner.manager.service.TradProdPropService;
import com.sq.partner.manager.util.DateUtil;
import com.sq.partner.manager.util.EncryptUtil;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.QRcodeUtil;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import com.google.gson.JsonArray;

import fr.opensagres.xdocreport.document.json.JSONArray;

/**
 * 激活卡激活
 * 
 * SQ
 *
 */
@Controller
@RequestMapping(value = "/activatedCard")
public class ActirationCardActivatedController {
    private static Logger logger = LogUtil
            .getLog(ActirationCardActivatedController.class);

    @Resource
    private ActirationCardActivatedService activatedService;
    @Resource
    private TradProdPropService tradProdPropService;
    @Resource
    private ActirationCardPreviewService previewService;
    @Resource
    private NlifeRiskService nlifeRiskService;
    @Resource
    private FacadeTempPolicyService facadeTempPolicyService;
    @Resource
    private FacadeAppFormDao facadeAppFormDao;
    @Resource
    private CardInfoDao cardInfoDao;
    @Resource
    private ActirationCardApplyService actirationCardApplyService;
    @Resource
    private FacadeTempPolicyDao facadeTempPolicyDao;

    /**
     * 激活卡激活选择页面
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/index")
    public String indexLoad() throws Exception {
        return "actirationCard/activatedCard/index";
    }

    /**
     * 个单激活-卡号密码验证
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Result singleLoginCheck(HttpSession session, String cardNo,
            String password, String flag) throws Exception {

        logger.info("激活-卡号密码验证开始");
        // 校验卡号和密码是否有值
        if (StrUtil.isEmpty(cardNo)) {
            return Result.error("请输入卡号");
        }
        if (StrUtil.isEmpty(password)) {
            return Result.error("请输入密码");
        }
        // 验证卡号和密码是否正确,正确的话取得产品信息
        Result result = activatedService.checkCard(cardNo, password);
        if ("success".equals(result.getResult())) {
            CardInfo cardInfo = (CardInfo) result.getData();
            // 用户信息
            GatewayUser gatewayuser = (GatewayUser) session
                    .getAttribute(Constants.SESSION_USER);
            // 机构代码校验
            if (!gatewayuser.getUserComcode().equals(cardInfo.getDeptNo())) {
                return Result.error("卡单不属于此机构，不可在此激活！");
            }
            // 查询此卡单关联的方案和产品信息
            ActirationCardActivated prodInfo = activatedService
                    .getProdInfoByPlanNo(cardInfo.getPlanNo());
            if (prodInfo == null) {
                return Result.error("卡单没有有效的方案和产品信息");
            }
            prodInfo.setCardInfo(cardInfo);
            prodInfo.setPricelessType(cardInfo.getPricelessType());
            if (!"Y".equals(prodInfo.getIsSeeMoney())) {
                return Result.error("卡单暂不支持非见费出单！");
            }
            // 个单
            if ("1".equals(flag)) {
                if ("1".equals(prodInfo.getAppType())) {
                    return Result.error("请选择团单投保流程！");
                }
            }
            // 团单
            if ("2".equals(flag)) {
                if ("0".equals(prodInfo.getAppType())&&!((StrUtil.isNotEmpty(prodInfo.getSpecialInfo())&&"0".equals(prodInfo.getSpecialInfo())))) {
                    return Result.error("请选择个单投保流程！");
                }
            }
            if ((StrUtil.isNotEmpty(prodInfo.getSpecialInfo())&&!"0".equals(prodInfo.getSpecialInfo()))|| (StrUtil.isNotEmpty(prodInfo.getRiskMainType()) 
            		&& !("2".equals(prodInfo.getRiskMainType())|| "7".equals(prodInfo.getRiskMainType()) || "9".equals(prodInfo.getRiskMainType())))) {
               System.out.print("****"+prodInfo.getRiskMainType());
            	return Result.error("目前投保只支持一般驾乘险、乘意险和驾意险！");
            }else if(StrUtil.isNotEmpty(prodInfo.getSpecialInfo())&&"0".equals(prodInfo.getSpecialInfo())&&"2".equals(prodInfo.getRiskMainType())){
            	cardInfo.setType("1");
            }
            
            if (!StrUtil.isEmpty(cardInfo.getStagNo())) {
                int count = activatedService.queryCardCountByStagNo(cardInfo.getStagNo());
                if (count > 1) {
                    return Result.error("卡号："+cardNo+"是在批量流程激活，请前往批量投保查看！");
                }
            }
            session.setAttribute("prodInfo", prodInfo);
        }
        logger.info("激活-卡号密码验证正常结束");
        return result;
    }

    /**
     * 个单激活页面初期化
     * 
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/single/add", method = RequestMethod.GET)
    public String singleAddLoad(HttpSession session, ModelMap model,
            String stagNo, String editFlag) throws Exception {
        logger.info("个单激活页面初期化开始");

        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        CardInfo cardInfo = prodInfo.getCardInfo();
        if (StrUtil.isEmpty(editFlag) && !StrUtil.isEmpty(cardInfo.getStagNo())) {
            stagNo = EncryptUtil.encrypt(cardInfo.getStagNo());
            model.put("stagNo", stagNo);
            model.put("editFlag", "edit");
        } else if (!StrUtil.isEmpty(stagNo)) {
            model.put("stagNo", stagNo);
            model.put("editFlag", "edit");
        }
        String url = null;
        // 存在暂存单时,查询投保单表、投保单扩展表、投保信息表、被保险人信息表、受益人信息表
        if (!StrUtil.isEmpty(stagNo)) {
            FacadeTempPolicy facadeTempPolicy = facadeTempPolicyService
                    .getFacadeTempPolicy(EncryptUtil.decrypt(stagNo));
            session.setAttribute("stagNoJm", stagNo);
            if ("12".equals(facadeTempPolicy.getStatus())
                    || "14".equals(facadeTempPolicy.getStatus())
                    || "11".equals(facadeTempPolicy.getStatus())
                    || "13".equals(facadeTempPolicy.getStatus())
                    || "02".equals(facadeTempPolicy.getStatus())) {
                // 到结果页面
                return "redirect:/pay/resultNlife?pricelessType="
                        + cardInfo.getPricelessType() + "&type=1";
            } else {
                // 到投保页面
                url = "actirationCard/activatedCard/single/add";
            }
            Map<String, Object> map = activatedService
                    .queryAllObjectMessage(EncryptUtil.decrypt(stagNo));
            FacadeAppForm facadeAppForm = (FacadeAppForm) map
                    .get("facadeAppForm");
            model.put("appNo", EncryptUtil.encrypt(facadeAppForm.getAppNo()));
            model.put("stagNo", stagNo);
            // 时间处理
            String effDate = DateUtil.format(facadeAppForm.getEffDate(),
                    "yyyy-MM-dd ") + facadeAppForm.getEffHours() + ":00:00";
            String termDate = DateUtil.format(facadeAppForm.getTermDate(),
                    "yyyy-MM-dd ") + facadeAppForm.getTermHours() + ":00:00";
            model.put("effDate", effDate);
            model.put("termDate", termDate);
            FacadeAppForm appForm = (FacadeAppForm) map.get("facadeAppForm");
            FacadeAppFormExtend extend = (FacadeAppFormExtend) map
                    .get("facadeAppFormExtend");
            FacadeAppApplicant applicant = (FacadeAppApplicant) map
                    .get("facadeAppApplicant");
            List<FacadeAppInsured> list = (List<FacadeAppInsured>) map
                    .get("facadeAppInsured");
            if (list != null && list.size() != 0) {
                model.put("facadeAppInsured", list.get(0));
            }
            model.put("facadeAppForm", appForm);
            model.put("facadeAppFormExtend", extend);
            model.put("facadeAppApplicant", applicant);
            // 激活卡没有受益人信息，指定法定受益人
        } else {
            // 到投保页面
            url = "actirationCard/activatedCard/single/add";
        }

        // 是否法定
        String lagalFalg = "1";
        // 查询所有证件类型
        List<DictDto> idTypeList = DictCache.getDict("NLife_Id_Type");

        // 查询所有国籍
        List<DictDto> nationalityList = DictCache.getDict("nationality");

        // 查询两者之间的类型
        List<DictDto> relaList = DictCache.getDict("NLife_Rela");

        // if ("0".equals(prodInfo.getSpecialInfo())) {
        // // 麻醉类型
        // List<DictDto> anesthTypeList =
        // DictCache.getDict("NLife_EleCodeType");
        // model.put("anesthTypeList", anesthTypeList);
        // }
        // if (Constants.PROD_TYPE_1.equals(prodInfo.getRiskMainType())) {
        // // 查询学平险信息
        // List<DictDto> studentTypeList = DictCache.getDict("student_type");
        // List<DictDto> schoolTypeList = DictCache.getDict("school_type");
        // List<DictDto> schoolNatureList = DictCache.getDict("school_nature");
        // model.put("studentTypeList", studentTypeList);
        // model.put("schoolTypeList", schoolTypeList);
        // model.put("schoolNatureList", schoolNatureList);
        // } else if (Constants.PROD_TYPE_6.equals(prodInfo.getRiskMainType()))
        // {
        // //还款方式
        // List<DictDto> loanWayList = DictCache.getDict("LOAN_WAY");
        // //保额确定方式
        // List<DictDto> repaidTypeList = DictCache.getDict("REPAID_TYPE");
        // model.put("loanWayList", loanWayList);
        // model.put("repaidTypeList", repaidTypeList);
        // } else if (Constants.PROD_TYPE_7.equals(prodInfo.getRiskMainType()))
        // {
        // //交通工具
        // List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
        // model.put("vehicleList", vehicleList);
        // } else if (Constants.PROD_TYPE_8.equals(prodInfo.getRiskMainType()))
        // {
        // //交通工具
        // List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
        // model.put("vehicleList", vehicleList);
        // //保障期间
        // List<DictDto> rationPeriodList =
        // DictCache.getDict("NLife_RationPeriod");
        // model.put("rationPeriodList", rationPeriodList);
        // } else if (Constants.PROD_TYPE_9.equals(prodInfo.getRiskMainType()))
        // {
        // //车辆性质
        // List<DictDto> vehicleNatureList =
        // DictCache.getDict("NLife_VehicleNature");
        // model.put("vehicleNatureList", vehicleNatureList);
        // }
        if (Constants.PROD_TYPE_2.equals(prodInfo.getRiskMainType())||Constants.PROD_TYPE_9.equals(prodInfo.getRiskMainType())) {
            // 车辆使用性质
            List<DictDto> useNatureList = DictCache.getDict("useNatureName");
            model.put("useNatureList", useNatureList);
            // 车辆性质
            List<DictDto> vehicleNatureList = DictCache
            		.getDict("NLife_VehicleNature");
            // model.put("vehicleNatureList", vehicleNatureList);
	        List<DictDto> mainVehicleNatureList = DictCache.getDict("MAIN_VEHICLE_NATURE");
	        model.put("mainVehicleNatureList", mainVehicleNatureList);
        } else if (Constants.PROD_TYPE_7.equals(prodInfo.getRiskMainType())) {
            // 交通工具
            List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
            model.put("vehicleList", vehicleList);
        } 
        sortidType(idTypeList, model);
//        model.put("idTypeList1", idTypeList);
        model.put("insuInfo", prodInfo);
        model.put("LAGALFALG", lagalFalg);
        model.put("nationalityList", nationalityList);
        model.put("relaList", relaList);

        logger.info("个单激活页面初期化正常结束");

        return url;
    }

    /**
     * 个人出单暂存信息接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/single/saveTemporary")
    @ResponseBody
    public Result saveTemporary(String baseInfo, String appLicant,
            String insured, String beneficiary, String stagNoJm,
            String appNoJm, HttpSession session) throws Exception {
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        // 卡号
        String cardNo = prodInfo.getCardInfo().getCardNo();
        Result result = saveOrUpdateBasicInformation(baseInfo, appLicant,
                insured, beneficiary, appNoJm, stagNoJm,
                prodInfo.getIsSeeMoney(), gatewayuser, prodInfo, "个单投保");
        if (!"success".equals(result.getResult())) {
            return result;
        }
        String stagNoAndappNo = (String) result.getData();
        if (StrUtil.isEmpty(stagNoJm)) {
            if (StrUtil.isEmpty(stagNoAndappNo)) {
                return Result.error("保存信息失败");
            }
            stagNoJm = EncryptUtil.encrypt(stagNoAndappNo.split(",")[0]);
            appNoJm = EncryptUtil.encrypt(stagNoAndappNo.split(",")[1]);

            // 卡单表更新暂存单号
            String stagString = stagNoAndappNo.split(",")[0];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("stagNo", stagString);
            paramMap.put("appNo", stagNoAndappNo.split(",")[1]);
            paramMap.put("cardNo", cardNo);
            activatedService.updateStagNoByCardNo(paramMap);
            CardInfo cardInfo = prodInfo.getCardInfo();
            cardInfo.setStagNo(stagString);
            prodInfo.setCardInfo(cardInfo);
            session.setAttribute("prodInfo", prodInfo);
        }
        logger.info("基本信息保存成功,生成暂存单号:" + stagNoJm);

        session.setAttribute("stagNoJm", stagNoJm);
        // 调用保费接口
        List<String> list = new ArrayList<String>();
        list.add(stagNoJm);
        list.add(appNoJm);
        FacadeTempPolicy facadeTempPolicy = new FacadeTempPolicy();
        facadeTempPolicy.setStagNo(EncryptUtil.decrypt(stagNoJm));
        try {
            // 保费试算
            result = previewService.computeFee(cardNo, facadeTempPolicy);
        } catch (Exception e) {
            logger.info(e);
            return Result.fail("保费试算失败，请联系管理员！");
        }
        logger.info("暂存单号:" + EncryptUtil.decrypt(stagNoJm) + "生成保费结果："
                + result.getMessage());
        if ("success".equals(result.getResult())) {
        	if(!"".equals(result.getData())&&result.getData()!=null){
        		session.setAttribute("warnInfo", result.getData());
        		list.add(result.getData().toString());
        	}else{
        		session.setAttribute("warnInfo", "");
        	}
            return Result.success("暂存成功", list);
        } else {
            result.setData(list);
        }
        return result;
    }

    /**
     * 个人出单投保预览
     * 
     * @param request
     * @param session
     * @param model
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/single/previewSingle")
    public String previewSingle(HttpSession session, ModelMap model)
            throws Exception {
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        String specialInfo = prodInfo.getSpecialInfo();
        String stagNoJm = (String) session.getAttribute("stagNoJm");
        String stagNo = EncryptUtil.decrypt(stagNoJm);
        model.put("stagNo", stagNoJm);
        Map<String, Object> map = activatedService
                .queryAllObjectMessage(stagNo);
        FacadeAppForm facadeAppForm = (FacadeAppForm) map.get("facadeAppForm");
        model.put("appNo", facadeAppForm.getAppNo());
        model.put("cardInfo", session.getAttribute("cardInfo"));
        // 时间处理
        String effDate = DateUtil.format(facadeAppForm.getEffDate(),
                "yyyy-MM-dd ") + facadeAppForm.getEffHours() + ":00:00";
        String termDate = DateUtil.format(facadeAppForm.getTermDate(),
                "yyyy-MM-dd ") + facadeAppForm.getTermHours() + ":00:00";
        model.put("effDate", effDate);
        model.put("termDate", termDate);
        model.put("pricelessType", prodInfo.getCardInfo().getPricelessType());
        model.put("planNo", prodInfo.getPlanNo());
        model.put("planName", prodInfo.getPlanName());
        FacadeAppForm appForm = (FacadeAppForm) map.get("facadeAppForm");
        FacadeAppFormExtend extend = (FacadeAppFormExtend) map
                .get("facadeAppFormExtend");
        FacadeAppApplicant applicant = (FacadeAppApplicant) map
                .get("facadeAppApplicant");
        List<FacadeAppInsured> list = (List<FacadeAppInsured>) map
                .get("facadeAppInsured");
        if (list != null && list.size() != 0) {
            model.put("facadeAppInsured", list.get(0));
        }
        FacadeTempPolicy tempPolicy = (FacadeTempPolicy) map
                .get("facadeTempPolicy");
        model.put("facadeAppForm", appForm);
        model.put("facadeAppFormExtend", extend);
        model.put("facadeAppApplicant", applicant);
        model.put("facadeTempPolicy", tempPolicy);
        model.put("global_SPECIAL_INFO", specialInfo);
        model.put("riskMainType", prodInfo.getRiskMainType());
        model.put("isLagal", 1);
        // 查询所有证件类型
        List<DictDto> idTypeList = DictCache.getDict("NLife_Id_Type");
        model.put("idTypeList", idTypeList);
        // 查询两者之间的类型
        List<DictDto> relaList = DictCache.getDict("NLife_Rela");
        model.put("relaList", relaList);
        // if ("0".equals(prodInfo.getSpecialInfo())) {
        // // 麻醉类型
        // List<DictDto> anesthTypeList =
        // DictCache.getDict("NLife_EleCodeType");
        // model.put("anesthTypeList", anesthTypeList);
        // }
        // if (Constants.PROD_TYPE_1.equals(prodInfo.getRiskMainType())) {
        // // 查询学平险信息
        // List<DictDto> studentTypeList = DictCache.getDict("student_type");
        // List<DictDto> schoolTypeList = DictCache.getDict("school_type");
        // List<DictDto> schoolNatureList = DictCache.getDict("school_nature");
        // model.put("studentTypeList", studentTypeList);
        // model.put("schoolTypeList", schoolTypeList);
        // model.put("schoolNatureList", schoolNatureList);
        // } else if (Constants.PROD_TYPE_6.equals(prodInfo.getRiskMainType()))
        // {
        // //还款方式
        // List<DictDto> loanWayList = DictCache.getDict("LOAN_WAY");
        // //保额确定方式
        // List<DictDto> repaidTypeList = DictCache.getDict("REPAID_TYPE");
        // model.put("loanWayList", loanWayList);
        // model.put("repaidTypeList", repaidTypeList);
        // } else if (Constants.PROD_TYPE_7.equals(prodInfo.getRiskMainType()))
        // {
        // //交通工具
        // List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
        // model.put("vehicleList", vehicleList);
        // } else if (Constants.PROD_TYPE_8.equals(prodInfo.getRiskMainType()))
        // {
        // //交通工具
        // List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
        // model.put("vehicleList", vehicleList);
        // //保障期间
        // List<DictDto> rationPeriodList =
        // DictCache.getDict("NLife_RationPeriod");
        // model.put("rationPeriodList", rationPeriodList);
        // } else if (Constants.PROD_TYPE_9.equals(prodInfo.getRiskMainType()))
        // {
        // //车辆性质
        // List<DictDto> vehicleNatureList =
        // DictCache.getDict("NLife_VehicleNature");
        // model.put("vehicleNatureList", vehicleNatureList);
        // }
        if (Constants.PROD_TYPE_2.equals(prodInfo.getRiskMainType())||Constants.PROD_TYPE_9.equals(prodInfo.getRiskMainType())) {
            // 车辆使用性质
            List<DictDto> useNatureList = DictCache.getDict("useNatureName");
            model.put("useNatureList", useNatureList);
            // 车辆性质
            /*List<DictDto> vehicleNatureList = DictCache
                    .getDict("NLife_VehicleNature");
            model.put("vehicleNatureList", vehicleNatureList);*/
	        List<DictDto> mainVehicleNatureList = DictCache.getDict("MAIN_VEHICLE_NATURE");
	        model.put("mainVehicleNatureList", mainVehicleNatureList);
        } else if (Constants.PROD_TYPE_7.equals(prodInfo.getRiskMainType())) {
            // 交通工具
            List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
            model.put("vehicleList", vehicleList);
        } 
        // 根据投保单号查询保险责任信息,特别约定
        List<Map<String, Object>> lists = nlifeRiskService
                .queryNlifeRiskAmt(appForm.getInsuPlanNo());
        model.put("planBaseLists", lists);
        model.put("warnInfo", session.getAttribute("warnInfo"));
        model.put("specialArran", lists.get(0).get("SPECIAL_ARRAN"));
        model.put("notice", lists.get(0).get("NOTICE"));
        return "actirationCard/activatedCard/single/preview";
    }

    /**
     * 个单确认投保
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/single/confirmSingle")
    public String confirmSingle(ModelMap model, HttpSession session,
            String cardNo) throws Exception {
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        CardInfo cardInfo = prodInfo.getCardInfo();
        FacadeTempPolicy sFacadeTempPolicy = new FacadeTempPolicy();
        String stagNo = (String) session.getAttribute("stagNoJm");
        sFacadeTempPolicy.setStagNo(EncryptUtil.decrypt(stagNo));
        sFacadeTempPolicy.setStatus("01,11,13");
        sFacadeTempPolicy = facadeTempPolicyService
                .findFacadeTempPolicy(sFacadeTempPolicy);
        // 卡单保费和保单保费判断
        if (!checkMoney(sFacadeTempPolicy.getAmount(), cardInfo.getTotPremamt())) {
            throw new AppException("卡单保费和保单保费不一致，不能投保");
        }
        // 核保试算,成功就跳转到支付页面
        FacadeTempPolicy facadeTempPolicy = activatedService.sendNlife(
                cardInfo, sFacadeTempPolicy);
        String isSeeMoney = facadeTempPolicy.getIsSeeMoney();
        String status = facadeTempPolicy.getStatus();
        // 如果是非见费出单，投保成功了就到支付结果页面
        if (!"Y".equals(facadeTempPolicy.getIsSeeMoney())
                && Constants.POL_STATUS_02.equals(status)) {
            return "redirect:/pay/resultNlife?pricelessType="
                    + cardInfo.getPricelessType() + "&type=1";
            // 如果是见费出单且是已支付状态，并且是有价激活卡,要做一次缴费确认
        } else if ("Y".equals(isSeeMoney)
                && Constants.POL_STATUS_12.equals(status)
                && "0".equals(cardInfo.getPricelessType())) {
            activatedService.updatePayCostCallBack(cardInfo.getCardNo(),
                    cardInfo.getCommamtId(), cardInfo.getStagNo(),
                    cardInfo.getTotPremamt());
            return "redirect:/pay/resultNlife?pricelessType="
                    + cardInfo.getPricelessType() + "&type=1";
        } else {
            model.put("facadeTempPolicy", facadeTempPolicy);
            model.put("isSeeMoney", isSeeMoney);
            model.put("pricelessType", cardInfo.getPricelessType());
            model.put("stag_No", stagNo);
            model.put("stagNo", EncryptUtil.decrypt(stagNo));
            model.put("cardNo", cardNo);
            return "actirationCard/activatedCard/single/confirm";
        }
    }

    /**
     * 暂存,投保接口共同处理基本信息方法
     * 
     * @param request
     * @param gatewayUser
     * @param cardNo
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private Result saveOrUpdateBasicInformation(String baseInfo,
            String appLicant, String insured, String beneficiary,
            String appNoJm, String stagNoJm, String isSeeMoney,
            GatewayUser gatewayUser, ActirationCardActivated card,
            String listName) throws Exception {
        logger.info("投保单表,投保单扩展表、投保人表,被保人表初始化开始");
        // 解析基本信息
        Map<String, Object> baseinfomap = JsonUtils.parseJson(baseInfo,
                Map.class);
        // 投保信息
        FacadeAppForm facadeAppForm = new FacadeAppForm();
        // 即时起保
        String realSignFlag = StrUtil.getVal(baseinfomap.get("realSignFlag"));
        // 投保起期
        String effDate = StrUtil.getVal(baseinfomap.get("effDate"));
        // 投保止期
        String termDate = StrUtil.getVal(baseinfomap.get("termDate"));
        // String insuredClientNo = StrUtil.getVal(baseinfomap
        // .get("insuredClientNo"));
        // // 麻醉类型
        // String anesthType = StrUtil.getVal(baseinfomap.get("anesthType"));
        // // 借款时间
        // String borrowTime = StrUtil.getVal(baseinfomap.get("borrowTime"));
        // // 还款时间
        // String repayTime = StrUtil.getVal(baseinfomap.get("repayTime"));
        // // 贷款银行网点名称
        // String loanBankSitename =
        // StrUtil.getVal(baseinfomap.get("loanBankSitename"));
        // // 银行联系人
        // String bankLinkerName =
        // StrUtil.getVal(baseinfomap.get("bankLinkerName"));
        // // 银行联系电话
        // String bankLinkerPhone =
        // StrUtil.getVal(baseinfomap.get("bankLinkerPhone"));
        // // 还款方式
        // String repaidType = StrUtil.getVal(baseinfomap.get("repaidType"));
        // // 保额确定方式
        // String loanWay = StrUtil.getVal(baseinfomap.get("loanWay"));
        // 缴费账户号
//        String payAccountNumber = StrUtil.getVal(baseinfomap
//                .get("payAccountNumber"));
//        // 缴费账户名
//        String payAccountName = StrUtil.getVal(baseinfomap
//                .get("payAccountName"));
//        // 开户行
//        String payBankAccount = StrUtil.getVal(baseinfomap
//                .get("payBankAccount"));
        String stagNo = "";
        String appNo = "";
        if (effDate.replace("-", "").replace(":", "").replace(" ", "").length() != 14) {
            return Result.error("起保日期格式不正确");
        }
        if (termDate.replace("-", "").replace(":", "").replace(" ", "")
                .length() != 14) {
            return Result.error("终保日期格式不正确");
        }
        if (StrUtil.isNotEmpty(stagNoJm)) {
            stagNo = EncryptUtil.decrypt(stagNoJm);
        } else if (StrUtil.isNotEmpty(card.getCardInfo().getStagNo())) {
            stagNo = card.getCardInfo().getStagNo();
        }
        if (StrUtil.isNotEmpty(appNoJm)) {
            appNo = EncryptUtil.decrypt(appNoJm);
        } else if (StrUtil.isNotEmpty(card.getCardInfo().getAppNo())) {
            appNo = card.getCardInfo().getAppNo();
        }
        facadeAppForm.setStagNo(stagNo);
        facadeAppForm.setAppNo(appNo);
        facadeAppForm.setInsuPlanNo(StrUtil.getVal(baseinfomap
                .get("insuPlanNo")));
        facadeAppForm.setInsuPlanNoDscp(StrUtil.getVal(baseinfomap
                .get("insuPlanNoDscp")));
        facadeAppForm.setRealSignFlag(realSignFlag);
        facadeAppForm.setUnirPp(Long.parseLong(StrUtil.getVal(baseinfomap
                .get("unirPp"))));
        String trip = StrUtil.getVal(baseinfomap.get("trip"));
        if (StrUtil.isEmpty(trip)) {
            trip = "无";
        }
        facadeAppForm.setTrip(trip);
        facadeAppForm.setStatus(Constants.POL_STATUS_01);
        if (StrUtil.isEmpty(stagNo)) {
            facadeAppForm.setInputDate(DateUtil
                    .getNowDate("yyyy-MM-dd HH:mm:ss"));
            facadeAppForm.setCreatTime(DateUtil.getNowTimestamp());
        } else {
            facadeAppForm.setUpdateTime(DateUtil.getNowTimestamp());
        }
        Date eDate = DateUtil.parse(effDate.substring(0, 10), "yyyy-MM-dd");
        Date tDate = DateUtil.parse(termDate.substring(0, 10), "yyyy-MM-dd");
        facadeAppForm.setEffDate(eDate);
        facadeAppForm.setEffHours(effDate.substring(11, 13));
        facadeAppForm.setTermDate(tDate);
        facadeAppForm.setTermHours(termDate.substring(11, 13));
        int dayCount = (int) ((tDate.getTime() - eDate.getTime()) / (24 * 60 * 60 * 1000));
        if ("00".equals(effDate.substring(11, 13))
                && "24".equals(termDate.substring(11, 13))) {
            dayCount = dayCount + 1;
        }
        facadeAppForm.setDayCount((long) dayCount);
        // Date eborrowTime = DateUtil.parse(borrowTime, "yyyy-MM-dd");
        // Date erepayTime = DateUtil.parse(repayTime, "yyyy-MM-dd");
        // facadeAppForm.setBorrowTime(eborrowTime);
        // facadeAppForm.setRepayTime(erepayTime);
        // facadeAppForm.setStringBorrowTime(borrowTime);
        // facadeAppForm.setStringRepayTime(repayTime);
        // facadeAppForm.setLoanBankSitename(loanBankSitename);
        // facadeAppForm.setBankLinkerName(bankLinkerName);
        // facadeAppForm.setBankLinkerPhone(bankLinkerPhone);
        // facadeAppForm.setRepaidType(repaidType);
        // facadeAppForm.setLoanWay(loanWay);
        // facadeAppForm.setPayAccountNumber(payAccountNumber);// 设置缴费账户号
        // facadeAppForm.setPayAccountName(payAccountName);// 设置缴费账户名
        // facadeAppForm.setPayBankAccount(payBankAccount);// 设置开户行
        facadeAppForm
                .setPartnerNo(StrUtil.getVal(baseinfomap.get("partnerNo")));
        facadeAppForm.setPartneSaleNo(StrUtil.getVal(baseinfomap
                .get("partnerNo")));
        // 投保单扩展信息（disputeType 争议处理方式，1：诉讼；2：仲裁）
        FacadeAppFormExtend extend = new FacadeAppFormExtend();
        extend.setAppNo(appNo);
        extend.setDisputeType(card.getDisputeType());
        // extend.setAnesthType(anesthType);
        if ("2".equals(card.getDisputeType())) {
            extend.setArbitrationDept(card.getArbitrationDept());
        } else {
            extend.setArbitrationDept("");
        }
	    // 新车辆性质
	    String mainVehicleNature = (String) baseinfomap.get("mainVehicleNature");
	    // 原车辆性质
	    String vehicleNature = "";
	    String userNature = "";
	    List<DictDto> mainVehicleNatureDictList = DictCache.getDict("MAIN_VEHICLE_NATURE");
	    for (DictDto dictDto : mainVehicleNatureDictList) {
		    if (dictDto.getCode().equals(mainVehicleNature)) {
			    vehicleNature = dictDto.getOtherCode();
			    userNature = dictDto.getOtherCode2();
		    }
	    }
	    extend.setMainVehicleNatureStr(mainVehicleNature);
	    extend.setMainVehicleNature(mainVehicleNature == null || "".equals(mainVehicleNature) ? null : mainVehicleNature.substring(0, 2));
	    // 车辆性质
	    // extend.setVehicleNature(StrUtil.getVal(baseinfomap.get("vehicleNature")));
	    extend.setVehicleNature(StrUtil.getVal(vehicleNature));
        // 驾乘险
        if (Constants.PROD_TYPE_2.equals(card.getRiskMainType())) {
	        // extend.setUseNature(StrUtil.getVal(baseinfomap.get("useNature")));
	        extend.setUseNature(StrUtil.getVal(userNature));
            extend.setSeatNum(StrUtil.getVal(baseinfomap.get("seatNum")));
            extend.setChassisNum(StrUtil.getVal(baseinfomap.get("chassisNum")));
            extend.setPlateNum(StrUtil.getVal(baseinfomap.get("plateNum")));
        }
        // 乘意险
        if (Constants.PROD_TYPE_7.equals(card.getRiskMainType())) {
            // || Constants.PROD_TYPE_8.equals(card.getRiskMainType())) {
            String departureTime = StrUtil.getVal(baseinfomap
                    .get("departureTime"));
            if (departureTime.replace("-", "").replace(":", "")
                    .replace(" ", "").length() != 14) {
                return Result.error("发车时间格式不正确");
            }
            extend.setTrainNumber(StrUtil.getVal(baseinfomap.get("trainNumber")));
            extend.setSeatNumber(StrUtil.getVal(baseinfomap.get("seatNumber")));
            extend.setDepartureDate(departureTime.substring(0, 10));
            extend.setDepartureHour(departureTime.substring(11, 19));
            extend.setArrivalTime(StrUtil.getVal(baseinfomap.get("arrivalTime")));
            extend.setTicketNo(StrUtil.getVal(baseinfomap.get("ticketNo")));
            extend.setTicketNumber(StrUtil.getVal(baseinfomap
                    .get("ticketNumber")));
            extend.setVehicle(StrUtil.getVal(baseinfomap.get("vehicle")));
            extend.setDepartureStation(StrUtil.getVal(baseinfomap
                    .get("departureStation")));
            extend.setArrivalStation(StrUtil.getVal(baseinfomap
                    .get("arrivalStation")));
            extend.setRationPeriod(StrUtil.getVal(baseinfomap
                    .get("rationPeriod")));
        }
        if (StrUtil.isEmpty(appNo)) {
            extend.setCreatTime(new Date());
            extend.setUpdateTime(new Date());
        } else {
            extend.setUpdateTime(new Date());
        }
        // 投保人信息
        FacadeAppApplicant facadeAppApplicant = JsonUtils.parseJson(appLicant,
                FacadeAppApplicant.class);

        if (facadeAppApplicant.getClientBir().length() != 10
                || facadeAppApplicant.getClientBir().replace("-", "").length() != 8) {
            return Result.error("投保人生日格式不正确");
        }
        facadeAppApplicant.setAppNo(appNo);
        if (StrUtil.isEmpty(stagNo)) {
            facadeAppApplicant.setCreatTime(DateUtil.getNowTimestamp());
        } else {
            facadeAppApplicant.setUpdateTime(DateUtil.getNowTimestamp());
        }

        // 被保人信息
        List<FacadeAppInsured> insuredList = new ArrayList<FacadeAppInsured>();
        FacadeAppInsured facadeAppInsured = null;
        List<Map<String, String>> insureds = JsonUtils.parseJson(insured,
                ArrayList.class);
	    // 记录超出限制的被保人名称
	    StringBuilder insuredNames = new StringBuilder();
	    // 份数限制功能，判断是否超出限制，超出为 true 
	    boolean exceedFlag = false;
        for (Map<String, String> map : insureds) {
            facadeAppInsured = new FacadeAppInsured();
            facadeAppInsured
                    .setClientName(StrUtil.getVal(map.get("clientName")));
            facadeAppInsured
                    .setIdTypeDesc(StrUtil.getVal(map.get("idTypeDesc")));
            facadeAppInsured.setIdType(StrUtil.getVal(map.get("idType")));
            facadeAppInsured.setIdNo(StrUtil.getVal(map.get("idNo")));
            facadeAppInsured.setClientTel(StrUtil.getVal(map.get("clientTel")));
            facadeAppInsured.setSex(StrUtil.getVal(map.get("sex")));
            facadeAppInsured.setClientBir(StrUtil.getVal(map.get("clientBir")));
            facadeAppInsured.setInsNationality(StrUtil.getVal(map
                    .get("insNationality")));
            facadeAppInsured.setAppNo(appNo);
            facadeAppInsured.setWorkType(StrUtil.getVal(map.get("workType")));
            // facadeAppInsured.setClientNo(insuredClientNo);
            if (StrUtil.isEmpty(stagNo)) {
                facadeAppInsured.setCreatTime(DateUtil.getNowTimestamp());
            } else {
                facadeAppInsured.setUpdateTime(DateUtil.getNowTimestamp());
            }
            if (facadeAppInsured.getClientBir().length() != 10
                    || facadeAppInsured.getClientBir().replace("-", "")
                            .length() != 8) {
                return Result.error("被保人出生日期格式不正确");
            }
	        // 查询需要份数限制功能的方案
	        List<DictDto> specialPlans = DictCache.getDict("jhcard_exceed_limit");
	        if (specialPlans != null && specialPlans.size() > 0) {
		        for (DictDto specialPlan : specialPlans) {
			        // 当前方案是否需要份数限制功能
			        if (specialPlan.getCode()!= null && specialPlan.getCode().equals(facadeAppForm.getInsuPlanNo()) && facadeAppInsured.getIdType().equals("01")) {
				        // 份数超出限制返回 true
				        if (activatedService.countCheck(facadeAppForm, facadeAppInsured)) {
					        // 记录超出限制的被保人名称
					        insuredNames.append(facadeAppInsured.getClientName());
					        insuredNames.append(" ");
					        // 超出限制
					        exceedFlag = true;
				        }
			        }
		        }
	        }
            insuredList.add(facadeAppInsured);
        }
	    if (exceedFlag) {
		    return Result.error("被保人 " + insuredNames + "超出份数限制！");
	    }
        // 驾乘险传车不传被保险人
        if (Constants.PROD_TYPE_2.equals(card.getRiskMainType())
                && insuredList.size() == 0) {
            facadeAppForm.setInsuredCount(Long.parseLong(extend.getSeatNum()));
        } else {
            facadeAppForm.setInsuredCount((long) insuredList.size());
        }
        facadeAppForm.setListName(listName);
        //
        // // 是否法定
        // String isLagal = StrUtil.getVal(baseinfomap.get("isLagal"));
        // // 受益人信息
        // List<FacadeAppBeneficiary> benefList = new
        // ArrayList<FacadeAppBeneficiary>();
        // FacadeAppBeneficiary benef;
        // DecimalFormat df = new DecimalFormat("0.00");
        // if (!"1".equals(isLagal)) {
        // String[] beneficiarys = beneficiary.split("\\|");
        // for (String benefStr : beneficiarys) {
        // if (StrUtil.isNotEmpty(benefStr)) {
        // String[] strs = benefStr.split(",");
        // benef = new FacadeAppBeneficiary();
        // //
        // clientName3+","+idType3+","+idNo3+","+clientBir3+","+sex3+","+bene_pct+","+bene_order+","+relWithInsured
        // benef.setClientName(strs[0]);
        // benef.setIdType(strs[1]);
        // benef.setIdNo(strs[2]);
        // String clientBir3 = strs[3];
        // if (StrUtil.isNotEmpty(clientBir3)) {
        // if (clientBir3.length() != 10
        // || clientBir3.replace("-", "").length() != 8) {
        // return Result.error("受益人出生日期格式不正确");
        // }
        // }
        // benef.setClientBir(clientBir3);
        // benef.setSex(strs[4]);
        // String benePct = df.format(Double.parseDouble(strs[5]));
        // benef.setBenePct(benePct);
        // benef.setRelWithInsured(strs[6]);
        // benef.setBenNationality(strs[7]);// 受益人国籍
        // benefList.add(benef);
        // }
        // }
        // }
        logger.info("投保单表,投保单扩展表、投保人表,被保人表初始化完成");
        Result result = activatedService.saveOrUpdateSingleTemporary(
                facadeAppForm, extend, facadeAppApplicant, insuredList,
                gatewayUser, card.getCardInfo().getCardNo(), isSeeMoney);
        return result;
    }

    /**
     * 电子保单url生成二维码
     * 
     * @param response
     * @param url
     */
    @RequestMapping(value = "/generateQRcode")
    public void generateQRcode(HttpServletResponse response, String url) {
        try {
            QRcodeUtil.QRcodeToStream(response, url, "", "", null, null);
        } catch (Exception e) {
            logger.info("生成二维码出错", e);
        }
    }

    /**
     * 团单页面初期化
     * 
     * @param session
     * @param model
     * @param stagNo
     * @param editFlag
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/group/add")
    public String groupLoad(HttpSession session, ModelMap model, String stagNo,
            String editFlag) throws Exception {
        logger.info("团单激活页面初期化开始");
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        model.put("prodInfo", prodInfo);
        CardInfo cardInfo = prodInfo.getCardInfo();
        if (StrUtil.isEmpty(stagNo) && !StrUtil.isEmpty(cardInfo.getStagNo())) {
            stagNo = EncryptUtil.encrypt(cardInfo.getStagNo());
            model.put("stagNo", stagNo);
            model.put("editFlag", "edit");
        } else if (!StrUtil.isEmpty(stagNo)) {
            model.put("stagNo", stagNo);
            model.put("editFlag", "edit");
        }
        String url = null;
        // 存在暂存单时,查询投保单表、投保单扩展表、投保信息表、被保险人信息表
        if (!StrUtil.isEmpty(stagNo)) {
            FacadeTempPolicy facadeTempPolicy = facadeTempPolicyService
                    .getFacadeTempPolicy(EncryptUtil.decrypt(stagNo));
            session.setAttribute("stagNoJm", stagNo);
            if ("12".equals(facadeTempPolicy.getStatus())
                    || "14".equals(facadeTempPolicy.getStatus())
                    || "11".equals(facadeTempPolicy.getStatus())
                    || "13".equals(facadeTempPolicy.getStatus())
                    || "02".equals(facadeTempPolicy.getStatus())) {
                // 到结果页面
                return "redirect:/pay/resultNlife?pricelessType="
                        + cardInfo.getPricelessType() + "&type=2";
            } else {
                // 到投保页面
                url = "actirationCard/activatedCard/group/add";
            }
        } else {
            // 到投保页面
            url = "actirationCard/activatedCard/group/add";
        }
        // 查询两者之间的类型
        List<DictDto> relaList = DictCache.getDict("NLife_Rela");
        model.put("relaList", relaList);
        // 证件类型
        List<DictDto> idTypeList = DictCache.getDict("NLife_Id_Type");
//        model.put("idTypeList", idTypeList);
        sortidType(idTypeList, model);
        // 查询所有国籍
        List<DictDto> nationalityList = DictCache.getDict("nationality");
        model.put("nationalityList", nationalityList);
        if (Constants.PROD_TYPE_2.equals(prodInfo.getRiskMainType())) {
            /*// 车辆使用性质
            List<DictDto> useNatureList = DictCache.getDict("useNatureName");
            model.put("useNatureList", useNatureList);*/
	        // 驾乘险新车辆性质
	        List<DictDto> mainVehicleNatureList = DictCache.getDict("MAIN_VEHICLE_NATURE");
			model.put("mainVehicleNatureList", mainVehicleNatureList);
        }

        return url;
    }

    /**
     * 查询投保信息
     * 
     * @param stagNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryAppFormInfo", method = RequestMethod.POST)
    @ResponseBody
    public Result selectAppFormInfo(String stagNo) throws Exception {
        if (StrUtil.isEmpty(stagNo)) {
            return Result.error("暂存单号不能为空");
        }
        Map<String, Object> map = activatedService
                .queryAllObjectMessage(EncryptUtil.decrypt(stagNo));
        if (map == null) {
            return Result.error("查询投保信息失败");
        }
        return Result.success(map);
    }

    /**
     * 团单出单暂存信息接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/group/saveTemporary")
    @ResponseBody
    public Result saveGroupTemporary(String baseInfo, String appLicant,
            String insureds, String stagNoJm, String appNoJm,
            HttpSession session) throws Exception {
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        // 卡号
        String cardNo = prodInfo.getCardInfo().getCardNo();
        Result result = saveOrUpdateBasicInformation(baseInfo, appLicant,
                insureds, null, appNoJm, stagNoJm, prodInfo.getIsSeeMoney(),
                gatewayuser, prodInfo, "团单投保");
        if (!"success".equals(result.getResult())) {
            return result;
        }
        String stagNoAndappNo = (String) result.getData();
        if (StrUtil.isEmpty(stagNoJm)) {
            if (StrUtil.isEmpty(stagNoAndappNo)) {
                return Result.error("保存信息失败");
            }
            stagNoJm = EncryptUtil.encrypt(stagNoAndappNo.split(",")[0]);
            appNoJm = EncryptUtil.encrypt(stagNoAndappNo.split(",")[1]);
            // insuredClientNo = stagNoAndappNo.split(",")[2];

            // 卡单表更新暂存单号
            String stagString = stagNoAndappNo.split(",")[0];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("stagNo", stagString);
            paramMap.put("appNo", stagNoAndappNo.split(",")[1]);
            paramMap.put("cardNo", cardNo);
            activatedService.updateStagNoByCardNo(paramMap);
            CardInfo cardInfo = prodInfo.getCardInfo();
            cardInfo.setStagNo(stagString);
            prodInfo.setCardInfo(cardInfo);
            session.setAttribute("cardInfo", cardInfo);
            session.setAttribute("prodInfo", prodInfo);
        }
        session.setAttribute("baseInfo", baseInfo);
        logger.info("基本信息保存成功,生成暂存单号:" + stagNoJm);
        session.setAttribute("stagNoJm", stagNoJm);
        // 调用保费接口
        List<String> list = new ArrayList<String>();
        list.add(stagNoJm);
        list.add(appNoJm);
        // list.add(insuredClientNo);
        FacadeTempPolicy facadeTempPolicy = new FacadeTempPolicy();
        facadeTempPolicy.setStagNo(EncryptUtil.decrypt(stagNoJm));
        try {
            // 保费试算
            result = previewService.computeFee(cardNo, facadeTempPolicy);
        } catch (Exception e) {
            logger.info(e);
            return Result.fail("保费试算失败，请联系管理员！");
        }
        logger.info("暂存单号:" + EncryptUtil.decrypt(stagNoJm) + "生成保费结果："
                + result.getMessage());
        if ("success".equals(result.getResult())) {
        	if(!"".equals(result.getData())&&result.getData()!=null){
        		session.setAttribute("warnInfo", result.getData());
        		list.add(result.getData().toString());
        	}else{
        		session.setAttribute("warnInfo", "");
        	}
            return Result.success("暂存成功", list);
        } else {
            result.setData(list);
        }
        return result;
    }

    /**
     * 团单出单暂存信息接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/group/previewGroup")
    public String previewGroup(HttpSession session, ModelMap model)
            throws Exception {

        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
       if("2".equals(prodInfo.getRiskMainType())){
    	   String baseInfo = (String) session.getAttribute("baseInfo");
    	   Map<String, Object> baseinfomap = JsonUtils.parseJson(baseInfo,Map.class);
    	   FacadeAppFormExtend extend = new FacadeAppFormExtend();
    	   // extend.setUseNature(StrUtil.getVal(baseinfomap.get("useNature")));
	       extend.setMainVehicleNature(StrUtil.getVal(baseinfomap.get("mainVehicleNature")));
    	   extend.setSeatNum(StrUtil.getVal(baseinfomap.get("seatNum")));
    	   extend.setChassisNum(StrUtil.getVal(baseinfomap.get("chassisNum")));
    	   extend.setPlateNum(StrUtil.getVal(baseinfomap.get("plateNum")));
    	   /*// 车辆使用性质
    	   List<DictDto> useNatureList = DictCache.getDict("useNatureName");
    	   model.put("useNatureList", useNatureList);*/
	       // 车辆性质
	       List<DictDto> mainVehicleNatureList = DictCache.getDict("MAIN_VEHICLE_NATURE");
		   model.put("mainVehicleNatureList",mainVehicleNatureList);
    	   model.put("extend", extend);
       }
        model.put("prodInfo", prodInfo);
        model.put("stagNo", session.getAttribute("stagNoJm"));
        model.put("warnInfo", session.getAttribute("warnInfo"));
        return "actirationCard/activatedCard/group/preview";
    }

    /**
     * 团单确认投保
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/group/confirmGroup")
    public String confirmGroup(ModelMap model, HttpSession session,
            String cardNo) throws Exception {
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        CardInfo cardInfo = prodInfo.getCardInfo();
        FacadeTempPolicy sFacadeTempPolicy = new FacadeTempPolicy();
        String stagNo = (String) session.getAttribute("stagNoJm");
        sFacadeTempPolicy.setStagNo(EncryptUtil.decrypt(stagNo));
        sFacadeTempPolicy.setStatus("01,11,13");
        sFacadeTempPolicy = facadeTempPolicyService
                .findFacadeTempPolicy(sFacadeTempPolicy);
        // 卡单保费和保单保费判断
        if (!checkMoney(sFacadeTempPolicy.getAmount(), cardInfo.getTotPremamt())) {
            throw new AppException("卡单保费和保单保费不一致，不能投保");
        }
        // 核保试算,成功就跳转到支付页面
        FacadeTempPolicy facadeTempPolicy = activatedService.sendNlife(
                cardInfo, sFacadeTempPolicy);
        String isSeeMoney = facadeTempPolicy.getIsSeeMoney();
        String status = facadeTempPolicy.getStatus();
        // 如果是非见费出单，投保成功了就到支付结果页面
        if (!"Y".equals(facadeTempPolicy.getIsSeeMoney())
                && Constants.POL_STATUS_02.equals(status)) {
            return "redirect:/pay/resultNlife?pricelessType="
                    + cardInfo.getPricelessType() + "&type=2";
            // 如果是见费出单且是已支付状态，并且是有价激活卡,要做一次缴费确认
        } else if ("Y".equals(isSeeMoney)
                && Constants.POL_STATUS_12.equals(status)
                && "0".equals(cardInfo.getPricelessType())) {
            activatedService.updatePayCostCallBack(cardInfo.getCardNo(),
                    cardInfo.getCommamtId(), cardInfo.getStagNo(),
                    cardInfo.getTotPremamt());

            return "redirect:/pay/resultNlife?pricelessType="
                    + cardInfo.getPricelessType() + "&type=2";
        } else {
            model.put("facadeTempPolicy", facadeTempPolicy);
            model.put("isSeeMoney", isSeeMoney);
            model.put("pricelessType", cardInfo.getPricelessType());
            model.put("stag_No", stagNo);
            model.put("stagNo", EncryptUtil.decrypt(stagNo));
            model.put("cardNo", cardNo);
            return "actirationCard/activatedCard/group/confirm";
        }
    }

    /**
     * 卡号中的暂存单号置空，重新投保
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/repeatActive")
    @ResponseBody
    public Result deleteBatchByStagNo(String stagNo) throws Exception {
        if (StrUtil.isEmpty(stagNo)) {
            return Result.error("暂存单号为空，请重新登录！");
        }
        stagNo = EncryptUtil.decrypt(stagNo);
        return activatedService.deleteBatchByStagNo(stagNo);
    }

    /**
     * 查询投保信息
     * 
     * @param stagNoJm
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryAppForm", method = RequestMethod.POST)
    @ResponseBody
    public Result queryAppForm(String stagNoJm) throws Exception {
        if (StrUtil.isEmpty(stagNoJm)) {
            return Result.error("暂存单号不能为空");
        }
        String stagNo = EncryptUtil.decrypt(stagNoJm);
        FacadeAppForm form = facadeAppFormDao
                .queryNLifeSingleFacadeAppFormByStagNo(stagNo);
        if (form == null) {
            return Result.error("没有投保信息");
        }
        return Result.success(form);
    }

    /**
     * 查询投保信息
     * 
     * @param appNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryRiskList", method = RequestMethod.POST)
    @ResponseBody
    public Result queryRiskList(String planNo) throws Exception {
        // 根据投保单号查询保险责任信息,特别约定
        List<Map<String, Object>> lists = nlifeRiskService
                .queryNlifeRiskAmt(planNo);
        if (lists == null || lists.size() == 0) {
            return Result.error("没有条款责任信息");
        }
        return Result.success(lists);
    }

    private boolean checkMoney(BigDecimal polAmount, BigDecimal cardAmount) {
        if (polAmount != null && cardAmount != null
                && polAmount.compareTo(cardAmount) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询当前职业分类下的职业名称
     * 
     * @param session
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryWorkTree", method = RequestMethod.POST)
    @ResponseBody
    public List<DictOccupDto> queryWorkTree(HttpSession session, String id)
            throws Exception {
        if (StrUtil.isEmpty(id)) {
            id = null;
        }
        return activatedService.queryWorkTree(id);
    }

    /**
     * 批量激活根据机构查询已关联该机构的激活卡模板
     * 
     * @param session
     * @param page
     * @param actirationCardDifinition
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/querycarddefine", method = RequestMethod.POST)
    @ResponseBody
    public Page<ActirationCardDifinition> queryCardDefineList(
            HttpSession session, Page<ActirationCardDifinition> page,
            ActirationCardDifinition actirationCardDifinition) throws Exception {
        // 获取当前登录user
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
        paramMap.put("depno", gatewayuser.getUserComcode().substring(0, 2));
        if (actirationCardDifinition.getId() != null) {
            paramMap.put("id", actirationCardDifinition.getId());
        }
        if (StrUtil.isNotEmpty(actirationCardDifinition.getName())) {
            paramMap.put("name", "%"+ actirationCardDifinition.getName() +"%");
        }
        page.setMap(paramMap);
        page = actirationCardApplyService.queryDefineByRegion(page);
        return page;
    }
    


    /**
     * 批量激活页面
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/batch/add")
    public String batchAdd(ModelMap model, HttpSession session,String stagNo)
            throws Exception {

        String url = null;
        // 存在暂存单时,查询投保单表、投保单扩展表、投保信息表、被保险人信息表
        if (!StrUtil.isEmpty(stagNo)) {
            FacadeTempPolicy facadeTempPolicy = facadeTempPolicyService
                    .getFacadeTempPolicy(stagNo);
            session.setAttribute("stagNoJm", EncryptUtil.encrypt(stagNo));
            ActirationCardActivated prodInfo = (ActirationCardActivated) session
                    .getAttribute("prodInfo");
            model.put("prodInfo", prodInfo);
            if ("12".equals(facadeTempPolicy.getStatus())
                    || "14".equals(facadeTempPolicy.getStatus())
                    || "11".equals(facadeTempPolicy.getStatus())
                    || "13".equals(facadeTempPolicy.getStatus())
                    || "02".equals(facadeTempPolicy.getStatus())) {
                // 到结果页面
                return "redirect:/pay/resultNlife?pricelessType="
                        + prodInfo.getPricelessType() + "&type=3";
            } else {
                // 到投保页面
                url = "actirationCard/activatedCard/batch/add";
                //取得投保信息list
                //TODOactivatedService
                List<ActirationCardBatchInsuredDto> list = activatedService
                        .getBatchInsuredList(stagNo);
                String insuredList = JsonUtils.toJson(list);
                model.put("insuredList", insuredList);
                model.put("stagNo", stagNo);
            }
        } else {
            // 到投保页面
            url = "actirationCard/activatedCard/batch/add";
        }

        // 查询所有证件类型
        List<DictDto> idTypeList = DictCache.getDict("NLife_Id_Type");

        // 查询所有国籍
        List<DictDto> nationalityList = DictCache.getDict("nationality");

        // 查询两者之间的类型
        List<DictDto> relaList = DictCache.getDict("NLife_Rela");
        // 车辆使用性质
        List<DictDto> useNatureList = DictCache.getDict("useNatureName");
        model.put("useNatureList", useNatureList);
        // 交通工具
        List<DictDto> vehicleList = DictCache.getDict("NLife_Vehicle");
        model.put("vehicleList", vehicleList);
        // 车辆性质
        /*List<DictDto> vehicleNatureList = DictCache
                .getDict("NLife_VehicleNature");*/
	    List<DictDto> mainVehicleNatureList = DictCache
			    .getDict("MAIN_VEHICLE_NATURE");
        model.put("mainVehicleNatureList", mainVehicleNatureList);
        sortidType(idTypeList, model);
//        model.put("idTypeList1", idTypeList);
        model.put("nationalityList", nationalityList);
        model.put("relaList", relaList);
        return url;
    }

    /**
     * 根据选中的卡定义查询产品和方案信息
     * 
     * @param session
     * @param planNo
     * @param name
     * @param id
     * @param pricelessType
     * @param modalPremamtPp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryProdInfoByPlanNo")
    @ResponseBody
    public Result queryProdInfoByPlanNo(HttpSession session, String planNo,
            String name, String id, String pricelessType, String modalPremamtPp)
            throws Exception {
        // 查询此卡单关联的方案和产品信息
        ActirationCardActivated prodInfo = activatedService
                .getProdInfoByPlanNo(planNo);
        if (prodInfo == null) {
            return Result.error("卡单没有有效的方案和产品信息");
        }
        if (!"Y".equals(prodInfo.getIsSeeMoney())) {
            return Result.error("卡单暂不支持非见费出单！");
        }
//        if ("1".equals(prodInfo.getAppType())) {
//            return Result.error("团单投保暂不支持批量投保流程！");
//        }
      if ((StrUtil.isNotEmpty(prodInfo.getSpecialInfo())) && !("0".equals(prodInfo.getSpecialInfo())) || (StrUtil.isNotEmpty(prodInfo.getRiskMainType()) && !( 
		"2".equals(prodInfo.getRiskMainType()) || "7".equals(prodInfo.getRiskMainType()) || "9" .equals(prodInfo.getRiskMainType())))) {
    	  return Result.error("目前投保只支持一般驾乘险、乘意险和驾意险！");
}
        prodInfo.setId(id);
        prodInfo.setName(name);
        prodInfo.setPricelessType(pricelessType);
        prodInfo.setTotPremamt(new BigDecimal(modalPremamtPp));
        session.setAttribute("prodInfo", prodInfo);
        return Result.success(prodInfo);

    }

    /**
     * 批量激活-卡号密码验证
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/checkCard")
    @ResponseBody
    public Result checkCard(HttpSession session, String cardNo,
            String cardPw, String cardDefineId,String editflag) throws Exception {

        logger.info("批量激活-卡号密码验证开始");
        // 校验卡号和密码是否有值
        if (StrUtil.isEmpty(cardNo)) {
            return Result.error("请输入卡号");
        }
        if (StrUtil.isEmpty(cardPw)) {
            return Result.error("请输入密码");
        }
        // 验证卡号和密码是否正确
        CardInfo card = cardInfoDao.getCardInfoByCardNo(cardNo);
        if (card == null) {
            return Result.error("卡号不正确！");
        }
        if (!cardPw.equals(card.getCardPw())) {
            return Result.error("密码不正确！");
        }
        if (!Constants.PROD_TYPE_NLIFE.equals(card.getTypeCode())) {
            return Result.error("激活卡系统目前只支持新意健险激活卡激活！");
        }
        if (!Constants.ACTIR_CARD_ACTIVABLE.equals(card.getStatus())) {
            return Result.error("卡号：" + cardNo + "不是可激活状态，不可激活！");
        }
        if (!cardDefineId.equals(card.getCardDefineId())) {
            return Result.error("卡号：" + cardNo + "跟您选择的卡定义名称不一致！");
        }
        if (StrUtil.isEmpty(card.getPlanNo())) {
            return Result.error("卡号：" + cardNo + "没有关联方案，请联系管理员！");
        }
//        if (!StrUtil.isEmpty(card.getStagNo())) {
//            return Result.error("卡号：" + cardNo + "已存在暂存单！");
//        }
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        // 机构代码校验
        if (!gatewayuser.getUserComcode().equals(card.getDeptNo())) {
            return Result.error("卡号：" + cardNo + "不属于此机构，不可在此激活！");
        }
        if (StrUtil.isEmpty(editflag) && !StrUtil.isEmpty(card.getStagNo())) {
            return Result.error("卡号："+cardNo+"存在暂存单，请查找暂存单继续投保！");
        }
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        prodInfo.setName(card.getName());
        prodInfo.setId(card.getCardDefineId());
        prodInfo.setPricelessType(card.getPricelessType());
        prodInfo.setTotPremamt(card.getTotPremamt());
        session.setAttribute("prodInfo", prodInfo);
        logger.info("批量激活-卡号密码验证正常结束");
        return Result.success("卡号密码验证成功");
    }

    /**
     * 批量出单投保信息暂存
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/batch/saveTemporary")
    @ResponseBody
    public Result saveTemporaryBatch(String infos, HttpSession session, String stagNo)
            throws Exception {
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        List<Map<String, String>> insureList = JsonUtils.parseJson(infos,
                ArrayList.class);
        String cardNo = null;
        Result result = null;
        // 投保信息
        FacadeAppForm facadeAppForm = null;
        FacadeAppFormExtend extend = null;
        FacadeAppApplicant facadeAppApplicant = null;
        FacadeAppInsured insured = null;
        String isSeeMoney = prodInfo.getIsSeeMoney();
        Map<String, String> map = new HashMap<String,String>();
	    // 记录超出限制的被保人名称
	    StringBuilder insuredNames = new StringBuilder();
	    // 份数限制功能，判断是否超出限制，超出为 true 
	    boolean exceedFlag = false;
        for (int i=0; i < insureList.size(); i++) {
            map = insureList.get(i);
            cardNo = StrUtil.getVal(map.get("cardNo"));
            facadeAppForm = getAppForm(map);
            extend = getAppFormExtend(map, prodInfo);
            facadeAppApplicant = getAppApplicant(map);
            // 驾乘险传车不传被保险人
            if (Constants.PROD_TYPE_2.equals(prodInfo.getRiskMainType())) {
                facadeAppForm.setInsuredCount("".equals(extend.getSeatNum())  || extend.getSeatNum() == null ? 1 : Long.parseLong(extend
                        .getSeatNum()));
            } else {
                facadeAppForm.setInsuredCount(new Long(1));
            }
	        insured = getAppInsured(map);
            facadeAppForm.setListName("批量投保");
			// 查询需要份数限制功能的方案
	        List<DictDto> specialPlans = DictCache.getDict("jhcard_exceed_limit");
            result = activatedService.saveBatchTemporary(facadeAppForm, extend,
                    facadeAppApplicant, insured, gatewayuser, cardNo,
                    isSeeMoney, stagNo, i);
            if (!"success".equals(result.getResult())) {
                return result;
            }
            stagNo = (String) result.getData();
            if (specialPlans != null && insured != null && specialPlans.size() > 0) {
                for (DictDto specialPlan : specialPlans) {
                    // 当前方案是否需要份数限制功能
                    if (specialPlan.getCode()!= null && specialPlan.getCode().equals(facadeAppForm.getInsuPlanNo())) {
                        // 份数超出限制返回 true
                        if (activatedService.countCheckBatch(facadeAppForm, insured, stagNo)) {
                            // 记录超出限制的被保人名称
                            insuredNames.append(insured.getClientName());
                            insuredNames.append(" ");
                            // 超出限制
                            exceedFlag = true;
                        }
                    }
                }
            }
        }
	    if (exceedFlag) {
		    return Result.error("被保人 " + insuredNames + "超出份数限制！");
	    }
        if (!"success".equals(result.getResult())) {
            return result;
        }
        logger.info("批量投保的所有投保信息保存成功,生成暂存单号:" + stagNo);

        //session.setAttribute("stagNo", stagNo);
        // 调用保费接口
        FacadeTempPolicy facadeTempPolicy = new FacadeTempPolicy();
        facadeTempPolicy.setStagNo(stagNo);
        try {
            // 保费试算
            result = previewService.computeFee(null, facadeTempPolicy);
        } catch (Exception e) {
            logger.info(e);
            return Result.fail("保费试算失败，请联系管理员！");
        }
        logger.info("暂存单号:" + stagNo + "生成保费结果："
                + result.getMessage());
        if ("success".equals(result.getResult())) {
        	if(!"".equals(result.getData())&&result.getData()!=null){
        		session.setAttribute("warnInfo", result.getData());
        	}else{
        		session.setAttribute("warnInfo", "");
        	}
            return Result.success("暂存成功",stagNo);
        } else {
            result.setData(stagNo);
        }
        return result;
    }

    /**
     * 批量激活-投保单信息
     * 
     * @param map
     * @return
     * @throws Exception
     */
    private FacadeAppForm getAppForm(Map<String, String> map) throws Exception {
        FacadeAppForm facadeAppForm = new FacadeAppForm();

        // 即时起保
        facadeAppForm.setRealSignFlag(StrUtil.getVal(map.get("realSignFlag")));
        // 投保起期
        String effDate = StrUtil.getVal(map.get("effDate"));
        // 投保止期
        String termDate = StrUtil.getVal(map.get("termDate"));
        Date eDate = DateUtil.parse(effDate.substring(0, 10), "yyyy-MM-dd");
        Date tDate = DateUtil.parse(termDate.substring(0, 10), "yyyy-MM-dd");
        facadeAppForm.setEffDate(eDate);
        facadeAppForm.setEffHours(effDate.substring(11, 13));
        facadeAppForm.setTermDate(tDate);
        facadeAppForm.setTermHours(termDate.substring(11, 13));
        int dayCount = (int) ((tDate.getTime() - eDate.getTime()) / (24 * 60 * 60 * 1000));
        if ("00".equals(effDate.substring(11, 13))
                && "24".equals(termDate.substring(11, 13))) {
            dayCount = dayCount + 1;
        }
        // 保险天数
        facadeAppForm.setDayCount((long) dayCount);
        // 方案号
        facadeAppForm.setInsuPlanNo(StrUtil.getVal(map.get("insuPlanNo")));
        // 方案名称
        facadeAppForm.setInsuPlanNoDscp(StrUtil.getVal(map
                .get("insuPlanNoDscp")));
        facadeAppForm.setUnirPp(new Long(1));
        String trip = StrUtil.getVal(map.get("trip"));
        if (StrUtil.isEmpty(trip)) {
            trip = "无";
        }
        // 行程
        facadeAppForm.setTrip(trip);

        facadeAppForm.setStatus(Constants.POL_STATUS_01);
        facadeAppForm.setPartnerNo(StrUtil.getVal(map.get("partnerNo")));
        facadeAppForm.setPartneSaleNo(StrUtil.getVal(map.get("partnerNo")));
//        // 录入日期
//        facadeAppForm.setInputDate(DateUtil.getNowDate("yyyy-MM-dd HH:mm:ss"));
//        // 创建时间
//        facadeAppForm.setCreatTime(DateUtil.getNowTimestamp());
        return facadeAppForm;
    }

    /**
     * 批量激活-投保扩展信息
     * 
     * @param map
     * @param map
     *            card
     * @return
     */
    private FacadeAppFormExtend getAppFormExtend(Map<String, String> map,
            ActirationCardActivated card) {
        FacadeAppFormExtend extend = new FacadeAppFormExtend();
        extend.setDisputeType(card.getDisputeType());
        if ("2".equals(card.getDisputeType())) {
            extend.setArbitrationDept(card.getArbitrationDept());
        } else {
            extend.setArbitrationDept("");
        }
        // 车辆性质
        // extend.setVehicleNature(StrUtil.getVal(map.get("vehicleNature")));
	    String mainVehicleNature = map.get("mainVehicleNature");
	    // 原车辆性质
	    String vehicleNature = "";
		String useNature = "";
	    List<DictDto> mainVehicleNatureDictList = DictCache.getDict("MAIN_VEHICLE_NATURE");
	    for (DictDto dictDto : mainVehicleNatureDictList) {
		    if (dictDto.getCode().equals(mainVehicleNature)){
			    vehicleNature = dictDto.getOtherCode();
				useNature = dictDto.getOtherCode2();
		    }
	    }
		// 原车辆性质
	    extend.setVehicleNature(StrUtil.getVal(vehicleNature));
		extend.setMainVehicleNatureStr(mainVehicleNature);
		extend.setMainVehicleNature(mainVehicleNature == null || "".equals(mainVehicleNature) ? null : mainVehicleNature.substring(0, 2));
        // 驾乘险
        if (Constants.PROD_TYPE_2.equals(card.getRiskMainType())) {
            extend.setUseNature(StrUtil.getVal(useNature));
            extend.setSeatNum(StrUtil.getVal(map.get("seatNum")));
            extend.setChassisNum(StrUtil.getVal(map.get("chassisNum")));
            extend.setPlateNum(StrUtil.getVal(map.get("plateNum")));
        }
        // 乘意险
        if (Constants.PROD_TYPE_7.equals(card.getRiskMainType())) {
            String departureTime = StrUtil.getVal(map.get("departureTime"));
            extend.setTrainNumber(StrUtil.getVal(map.get("trainNumber")));
            extend.setSeatNumber(StrUtil.getVal(map.get("seatNumber")));
            extend.setDepartureDate(departureTime.substring(0, 10));
            extend.setDepartureHour(departureTime.substring(11, 19));
            extend.setArrivalTime(StrUtil.getVal(map.get("arrivalTime")));
            extend.setTicketNo(StrUtil.getVal(map.get("ticketNo")));
            extend.setTicketNumber(StrUtil.getVal(map.get("ticketNumber")));
            extend.setVehicle(StrUtil.getVal(map.get("vehicle")));
            extend.setDepartureStation(StrUtil.getVal(map
                    .get("departureStation")));
            extend.setArrivalStation(StrUtil.getVal(map.get("arrivalStation")));
            extend.setRationPeriod(StrUtil.getVal(map.get("rationPeriod")));
        }
        extend.setCreatTime(new Date());
        extend.setUpdateTime(new Date());
        return extend;
    }

    /**
     * 批量激活-投保人信息
     * 
     * @param map
     * @return
     */
    private FacadeAppApplicant getAppApplicant(Map<String, String> map) {
        FacadeAppApplicant facadeAppApplicant = new FacadeAppApplicant();

        facadeAppApplicant.setClientName(StrUtil.getVal(map.get("clientNameTbr")));
        facadeAppApplicant.setCertificateType(StrUtil.getVal(map
                .get("certificateTypeTbr")));
        facadeAppApplicant.setCertificateCode(StrUtil.getVal(map
                .get("certificateCodeTbr")));
        facadeAppApplicant.setLinkmanTel(StrUtil.getVal(map.get("linkmanTelTbr")));
        facadeAppApplicant.setSex(StrUtil.getVal(map.get("sexTbr")));
        facadeAppApplicant.setClientBir(StrUtil.getVal(map.get("clientBirTbr")));
        facadeAppApplicant.setAppNationality(StrUtil.getVal(map
                .get("appNationalityTbr")));
        facadeAppApplicant.setWorkType(StrUtil.getVal(map.get("workTypeTbr")));
        facadeAppApplicant.setRelWithInsured(StrUtil.getVal(map
                .get("relWithInsured")));
        facadeAppApplicant.setEmail(StrUtil.getVal(map.get("emailTbr")));
        facadeAppApplicant.setCreatTime(DateUtil.getNowTimestamp());
        facadeAppApplicant.setAppNature(StrUtil.getVal(map.get("tbrNature")));

        return facadeAppApplicant;
    }

    /**
     * 批量激活-被保人信息
     * 
     * @param map
     * @return
     */
    private FacadeAppInsured getAppInsured(Map<String, String> map) {
        // 被保人信息;
        FacadeAppInsured facadeAppInsured = new FacadeAppInsured();
        facadeAppInsured.setClientName(StrUtil.getVal(map.get("clientNameBbr")));
        facadeAppInsured.setIdType(StrUtil.getVal(map.get("idTypeBbr")));
        facadeAppInsured.setIdNo(StrUtil.getVal(map.get("idNoBbr")));
        facadeAppInsured.setClientTel(StrUtil.getVal(map.get("clientTelBbr")));
        facadeAppInsured.setSex(StrUtil.getVal(map.get("sexBbr")));
        facadeAppInsured.setClientBir(StrUtil.getVal(map.get("clientBirBbr")));
        facadeAppInsured.setInsNationality(StrUtil.getVal(map
                .get("insNationalityBbr")));
        facadeAppInsured.setWorkType(StrUtil.getVal(map.get("workTypeBbr")));
        facadeAppInsured.setCreatTime(DateUtil.getNowTimestamp());
        return facadeAppInsured;
    }

    /**
     * 批量出单投保预览
     * 
     * @param session
     * @param model
     * @param stagNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/batch/previewBatch")
    public String previewBatch(HttpSession session, ModelMap model,
            String stagNo) throws Exception {

        // 卡模板信息
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        model.put("prodInfo", prodInfo);

        // 暂存单信息
        FacadeTempPolicy facadetemppolicy = facadeTempPolicyService
                .getFacadeTempPolicy(stagNo);
        model.put("facadeTempPolicy", facadetemppolicy);

        // 暂存单下投保单数
        int appCount = activatedService.queryAppCountByStagNo(stagNo);
        model.put("appCount", appCount);
        // 卡总张数
        int cardCount = activatedService.queryCardCountByStagNo(stagNo);
        model.put("cardCount", cardCount);
        model.put("stagNo", stagNo);
        model.put("warnInfo", session.getAttribute("warnInfo"));
        return "actirationCard/activatedCard/batch/preview";
    }

    /**
     * 批量激活确认投保
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/batch/confirmBatch")
    public String confirmBatch(ModelMap model, HttpSession session,
            String stagNo) throws Exception {
        ActirationCardActivated prodInfo = (ActirationCardActivated) session
                .getAttribute("prodInfo");
        session.setAttribute("stagNoJm", EncryptUtil.encrypt(stagNo));
        FacadeTempPolicy sFacadeTempPolicy = new FacadeTempPolicy();
        sFacadeTempPolicy.setStagNo(stagNo);
        sFacadeTempPolicy.setStatus("01,02,11,12,13");
        sFacadeTempPolicy = facadeTempPolicyService
                .findFacadeTempPolicy(sFacadeTempPolicy);

        // 卡总张数
        int cardCount = activatedService.queryCardCountByStagNo(stagNo);
        // 卡单保费和保单保费判断
        if (!checkMoney(sFacadeTempPolicy.getAmount(),
                prodInfo.getTotPremamt().multiply(new BigDecimal(cardCount)))) {
            throw new AppException("总卡单保费和保单总保费不一致，不能投保");
        }
        String isSeeMoney = sFacadeTempPolicy.getIsSeeMoney();
        String status = sFacadeTempPolicy.getStatus();
        // 如果是非见费出单，投保成功了就到支付结果页面
        if (!"Y".equals(sFacadeTempPolicy.getIsSeeMoney())
                && Constants.POL_STATUS_02.equals(status)) {
            return "redirect:/pay/resultNlife?pricelessType="
                    + prodInfo.getPricelessType() + "&type=3";
        }
        
        // 取得暂存单下的投保单
        FacadeAppForm sfacadeAppForm = new FacadeAppForm();
        sfacadeAppForm.setStagNo(stagNo);
        // 根据暂存单号拿到保单所有数据
        List<FacadeAppForm> facadeAppForms = null;
        FacadeAppForm facadeAppForm = null;
        CardInfo cardInfo = null;
        // 如果是见费出单且是已支付状态，并且是有价激活卡,要做一次缴费确认
        if ("Y".equals(isSeeMoney) && Constants.POL_STATUS_12.equals(status)
                && "0".equals(prodInfo.getPricelessType())) {
            // 取录入，待支付，和支付失败的保单
            sfacadeAppForm.setStatus("12");
            facadeAppForms = facadeAppFormDao
                    .selectFacadeAppFormList(sfacadeAppForm);
            if (facadeAppForms != null && facadeAppForms.size() != 0) {
                facadeAppForm = facadeAppForms.get(0);
                // 根据暂存单号和投保单号取得卡单信息
                cardInfo = cardInfoDao.getCardInfoByAppNo(
                        facadeAppForm.getAppNo(), stagNo);
                // 缴费确认
                activatedService.updatePayCostCallBack(cardInfo.getCardNo(),
                        cardInfo.getCommamtId(), cardInfo.getStagNo(),
                        cardInfo.getTotPremamt());
            }

            return "redirect:/pay/resultNlife?pricelessType="
                    + prodInfo.getPricelessType() + "&type=3";
        } else {
            // 取录入，待支付，和支付失败的保单
            sfacadeAppForm.setStatus("01,11,13");
            facadeAppForms = facadeAppFormDao
                    .selectFacadeAppFormList(sfacadeAppForm);
            for (int i = 0; i < facadeAppForms.size(); i++) {
                facadeAppForm = facadeAppForms.get(i);
                facadeAppForm.setStringEffDate(DateUtil.format(
                        facadeAppForm.getEffDate(), "yyyy-MM-dd")
                        + " "
                        + (facadeAppForm.getEffHours() == null ? "00"
                                : facadeAppForm.getEffHours() + ":00:00"));
                facadeAppForms.set(i, facadeAppForm);
            }
            
            sFacadeTempPolicy.setFacadeAppForms(facadeAppForms);
            if(status.equals(Constants.POL_STATUS_01)){
                model.put("send",true);
            }else{
                model.put("send",false);
            }
            FacadeAppForm form = facadeAppForms.get(0);
            model.put("facadeAppForm", form);
            model.put("facadeTempPolicy", sFacadeTempPolicy);
            model.put("isSeeMoney", isSeeMoney);
            model.put("pricelessType", prodInfo.getPricelessType());
            model.put("stagNo", stagNo);
            model.put("stag_No", EncryptUtil.encrypt(stagNo));
            return "actirationCard/activatedCard/batch/confirm";
        }
    }
    @RequestMapping(value = "/sendNlife")
    @ResponseBody
    public Result sendLife(ModelMap model,HttpSession session,String appNo) throws Exception,AppException {
        logger.info("传入保单号:"+appNo);
        //解密
        appNo=EncryptUtil.decrypt(appNo);
        //取出一条投保状态为录入状态的保单
        FacadeAppForm facadeAppForm= facadeAppFormDao
                .queryFacadeAppFormByAppNo(appNo);
        //如果没有查到就通知前端 不用请求了
        if(null==facadeAppForm){
            return Result.error("投保单有误，请稍后重试！");
        }
        //判断投保单的状态
        String status=facadeAppForm.getStatus();
        if("01".equals(status)){
            facadeAppForm = activatedService.sendNlife1(facadeAppForm);
            return Result.success(facadeAppForm);
        }else{
            return Result.error("投保单有误，请稍后重试！");
        }
    }
    
    @RequestMapping(value = "/clickStatus")
    @ResponseBody
    public Result clickStatus(ModelMap model,HttpSession session,String stagNo) throws Exception,AppException {
        FacadeTempPolicy sFacadeTempPolicy = new FacadeTempPolicy();
        sFacadeTempPolicy.setStagNo(stagNo);
        sFacadeTempPolicy.setStatus("01,02,11,12,13");
        FacadeTempPolicy facadeTempPolicy=facadeTempPolicyDao.selectFacadeTempPolicy(sFacadeTempPolicy);
        if(null==facadeTempPolicy){
            return Result.error("暂存单错误");
        }
        return Result.success(facadeTempPolicy);
    }
    
    @RequestMapping(value = "/batch/deleteAppInfo")
    @ResponseBody
    public Result deleteAppInfo(String cardNo,String stagNo) throws Exception,AppException {
        
        return activatedService.deleteAppInfo(cardNo, stagNo);
    }
    


    /**
     * 批量激活-卡号密码验证
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/batch/checkCard")
    @ResponseBody
    public Result checkCardNo(HttpSession session, String cardNo,
            String cardPw) throws Exception {

        logger.info("批量激活-卡号密码验证开始");
        // 校验卡号和密码是否有值
        if (StrUtil.isEmpty(cardNo)) {
            return Result.error("请输入卡号");
        }
        if (StrUtil.isEmpty(cardPw)) {
            return Result.error("请输入密码");
        }
        // 验证卡号和密码是否正确
        CardInfo card = cardInfoDao.getCardInfoByCardNo(cardNo);
        if (card == null) {
            return Result.error("卡号不正确！");
        }
        if (!cardPw.equals(card.getCardPw())) {
            return Result.error("密码不正确！");
        }
        if (!Constants.PROD_TYPE_NLIFE.equals(card.getTypeCode())) {
            return Result.error("激活卡系统目前只支持新意健险激活卡激活！");
        }
        if (!Constants.ACTIR_CARD_ACTIVABLE.equals(card.getStatus())
                && !Constants.ACTIR_CARD_ACTIVABLE_USED.equals(card.getStatus())) {
            return Result.error("卡号：" + cardNo + "不是可激活状态，不可激活！");
        }
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        // 机构代码校验
        if (!gatewayuser.getUserComcode().equals(card.getDeptNo())) {
            return Result.error("卡号：" + cardNo + "不属于此机构，不可在此激活！");
        }
        if (StrUtil.isEmpty(card.getStagNo())) {
            return Result.error("卡号："+cardNo+"还没有投保，没有暂存单");
        }
        // 查询此卡单关联的方案和产品信息
        ActirationCardActivated prodInfo = activatedService
                .getProdInfoByPlanNo(card.getPlanNo());
        if (prodInfo == null) {
            return Result.error("卡单没有有效的方案和产品信息");
        }
        prodInfo.setId(card.getCardDefineId());
        prodInfo.setName(card.getName());
        prodInfo.setPricelessType(card.getPricelessType());
        prodInfo.setTotPremamt(card.getTotPremamt());
        session.setAttribute("prodInfo", prodInfo);
        logger.info("批量激活-卡号密码验证正常结束");
        return Result.success("卡号密码验证成功",card.getStagNo());
    }
    
    
    /**
	 * 批量激活模板下载
	 */
	@RequestMapping(value = "/downloadActivated", method = RequestMethod.GET)
	public void downloadCoreProd(HttpServletResponse response,HttpServletRequest request ) throws IOException{
		String classPath=this.getClass().getResource("").getPath();
		String path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/acticated_template.xls").replace("/WEB-INF", "");
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		try {
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			//清空response
			response.reset();
			//设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		}catch (Exception e) {
			logger.info(e);
		}finally{
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}
	
	/**
	 * excel上传
	 */
	@RequestMapping(value = "/xlsImportFileUpload")
	public void addNlifeCoreProdFile(@RequestParam MultipartFile[] myfiles,HttpServletResponse response, HttpSession session,String riskMainType,String cardDefineId) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		Page<String>  page = new Page<String>();
		PrintWriter out = null;
		Map<String, Object> dataMap = new HashMap<String, Object>();
		List<InputStream> inputStreams = null;
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			if (myfiles.length < 1) {
				//抛出异常 excel为空
				page.setResult("error");
				page.setMessage("Excel内容为空，请录入数据");
				dataMap.put("result", false);
			}else{
				inputStreams=activatedService.getFileInputStream(myfiles);
				Map<String, Object> mapData = activatedService.insertDataToPage(inputStreams.get(0),riskMainType,cardDefineId);
				if ("".equals(mapData.get("errorMsg"))||null==mapData.get("errorMsg")) {
					dataMap.put("result", true);
					dataMap.put("dataList", mapData.get("dataList"));
				}else{
					dataMap.put("result", false);
					dataMap.put("errorMsg", mapData.get("errorMsg"));
				}
			}
		} catch (Exception e) {
			logger.info("---------激活卡录单Excel导入失败----------",e);
			dataMap.put("result", false);
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(dataMap));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}
	
	void sortidType(List<DictDto> list,ModelMap model){
		List<DictDto> id01 = new ArrayList<DictDto>();
		List<DictDto> id02 = new ArrayList<DictDto>();
		List<DictDto> id03 = new ArrayList<DictDto>();
		for (DictDto dictDto : list) {
			if("NATURE".equals(dictDto.getOtherCode())){
				id01.add(dictDto);
			}else if("26".equals(dictDto.getCode())){
				id03.add(dictDto);
				id02.add(dictDto);
			}else{
				id02.add(dictDto);
			}
		}
		model.put("idNature", list);
		model.put("id01", JsonUtils.toJson(id01));
		model.put("id02", JsonUtils.toJson(id02));
		model.put("id03", JsonUtils.toJson(id03));
	}
	
}
